package cn.wowjoy.office.materialinspection.check.task.count.statistic;


import android.arch.lifecycle.Observer;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.View;

import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.DefaultValueFormatter;
import com.github.mikephil.charting.formatter.PercentFormatter;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import cn.wowjoy.office.R;
import cn.wowjoy.office.baselivedata.appbase.LiveDataWrapper;
import cn.wowjoy.office.baselivedata.appbase.NewBaseFragment;
import cn.wowjoy.office.common.widget.CreateDialog;
import cn.wowjoy.office.common.widget.MDialog;
import cn.wowjoy.office.data.response.CheckCountResponse;
import cn.wowjoy.office.databinding.FragmentStatisticBinding;
import cn.wowjoy.office.materialinspection.check.task.count.CheckCountViewModel;

/**
 * A simple {@link Fragment} subclass.
 */
public class StatisticFragment extends NewBaseFragment<FragmentStatisticBinding, CheckCountViewModel> {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private PieChart mPieChartCount;

    private PieChart mPieChartValue;
    private String taskId;
    private MDialog waitDialog;

    private List<Float> mMoneySum = new ArrayList<>();

    private List<Float> mNumberSum = new ArrayList<>();

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment HomeFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static StatisticFragment newInstance(String param1, String param2) {
        StatisticFragment statisticFragment = new StatisticFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        statisticFragment.setArguments(args);
        return statisticFragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    public StatisticFragment() {
        // Required empty public constructor
    }


    @Override
    protected Class<CheckCountViewModel> getViewModel() {
        return CheckCountViewModel.class;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_statistic;
    }



    @Override
    protected void onCreateViewLazy(Bundle savedInstanceState) {
        binding.setViewModel(viewModel);
        mPieChartCount = binding.chartCount;
        mPieChartValue = binding.chartValue;
        taskId = getActivity().getIntent().getStringExtra("taskId");
        viewModel.count(taskId);
        initObserver();

    }

    private int normalCount;
    private float normalSum;

    private int pankuiCount;
    private float pankuiSum;

    private int panyinCount;
    private float panyinSum;

    private void initObserver() {

        viewModel.getResponse()
                .observe(this, new Observer<LiveDataWrapper<CheckCountResponse>>() {
                    @Override
                    public void onChanged(@Nullable LiveDataWrapper<CheckCountResponse> countResponseLiveDataWrapper) {
                        switch (countResponseLiveDataWrapper.status) {
                            case LOADING:
                                waitDialog = CreateDialog.waitingDialog(getActivity());
                                break;
                            case SUCCESS:
                                waitDialog.dismiss();
                                Map<String, String> normal = countResponseLiveDataWrapper.data.getNormal();
                                Map<String, String> pankui = countResponseLiveDataWrapper.data.getPankui();
                                Map<String, String> panyin = countResponseLiveDataWrapper.data.getPanyin();
                                Set<String> normalSet = normal.keySet();
                                for (String key : normalSet) {
                                    if ("count".equals(key)) {
                                        normalCount = Integer.parseInt(normal.get(key));
                                    }
                                    if ("sumOriginalValue".equals(key)) {
                                        normalSum = Float.parseFloat(normal.get(key));
                                    }
                                }
                                Set<String> pankuiSet = pankui.keySet();
                                for (String key : pankuiSet) {
                                    if ("count".equals(key)) {
                                        pankuiCount = Integer.parseInt(pankui.get(key));
                                    }
                                    if ("sumOriginalValue".equals(key)) {
                                        pankuiSum = Float.parseFloat(pankui.get(key));
                                    }
                                }
                                Set<String> panyinSet = normal.keySet();
                                for (String key : panyinSet) {
                                    if ("count".equals(key)) {
                                        panyinCount = Integer.parseInt(panyin.get(key));
                                    }
                                    if ("sumOriginalValue".equals(key)) {
                                        panyinSum = Float.parseFloat(panyin.get(key));
                                    }
                                }
                                float sumCount = normalCount + panyinCount + pankuiCount;
                                Log.e("'PXY'", "normalCount: " + normalCount);
                                Log.e("'PXY'", "panyinCount: " + panyinCount);
                                Log.e("'PXY'", "pankuiCount: " + pankuiCount);
                                Log.e("'PXY'", "sum: " + sumCount);
                                ArrayList<PieEntry> entries = new ArrayList<PieEntry>();
                                entries.add(new PieEntry(normalCount, "正常: "+normalCount));
                                entries.add(new PieEntry(panyinCount, "盘盈: "+panyinCount));
                                entries.add(new PieEntry(pankuiCount, "盘亏: "+pankuiCount));
                                initChartView(mPieChartCount,true);
                                initLegend(mPieChartCount,true);
                                mPieChartCount.setData(setData(entries,2));
                                mPieChartCount.highlightValues(null);
                                if(entries.size() <= 0){
                                    mPieChartCount.setVisibility(View.GONE);
                                }
                                //刷新
                                mPieChartCount.invalidate();


                                Log.e("'PXY'", "normalSum: " + normalSum);
                                Log.e("'PXY'", "panyinSum: " + panyinSum);
                                Log.e("'PXY'", "pankuiSum: " + pankuiSum);
                                ArrayList<PieEntry> entriesValue = new ArrayList<PieEntry>();
                                entriesValue.add(new PieEntry(normalSum, "正常: "+normalSum));
                                entriesValue.add(new PieEntry(panyinSum, "盘盈: "+panyinSum));
                                entriesValue.add(new PieEntry(pankuiSum, "盘亏: "+pankuiSum));
                                if(entriesValue.size() <= 0){
                                    mPieChartValue.setVisibility(View.GONE);
                                }
                                initChartView(mPieChartValue,true);
                                initLegend(mPieChartValue,true);
                                mPieChartValue.setData(setData(entriesValue,2));
                                mPieChartValue.highlightValues(null);
                                //刷新
                                mPieChartValue.invalidate();



                                break;
                            case ERROR:
                                waitDialog.dismiss();
                                Throwable throwable = countResponseLiveDataWrapper.error;
                                handleException(throwable, false);
                                getActivity().finish();
                                break;
                        }
                    }
                });
    }


     public void initLegend(PieChart pieChart,boolean enabled){
         Legend l = pieChart.getLegend();
         l.setEnabled(enabled);                    //是否启用图列（true：下面属性才有意义）
//         l.setPosition(Legend.LegendPosition.BELOW_CHART_CENTER);
         l.setVerticalAlignment(Legend.LegendVerticalAlignment.CENTER);
         l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
         l.setOrientation(Legend.LegendOrientation.VERTICAL);
         l.setForm(Legend.LegendForm.SQUARE); //设置图例的形状
         l.setFormSize(8);                    //设置图例的大小
         l.setFormToTextSpace(getActivity().getResources().getDimension(R.dimen.piechart_legend_formtotextspace));            //设置每个图例实体中标签和形状之间的间距
         l.setDrawInside(false);
         l.setWordWrapEnabled(true);           //设置图列换行(注意使用影响性能,仅适用legend位于图表下面)
         l.setXEntrySpace(0);                //设置图例实体之间延X轴的间距（setOrientation = HORIZONTAL有效）
         l.setYEntrySpace(getActivity().getResources().getDimension(R.dimen.piechart_legend_xentryspace));                 //设置图例实体之间延Y轴的间距（setOrientation = VERTICAL 有效）
         l.setYOffset(0f);                     //设置比例块Y轴偏移量
         l.setXOffset(0f);
         l.setTextSize(getActivity().getResources().getDimension(R.dimen.piechart_legend_textsize));                   //设置图例标签文本的大小
         l.setTextColor(Color.parseColor("#4A4A4A"));//设置图例标签文本的颜色
     }
    public void initChartView(PieChart mPieChart,boolean usePercent) {
        mPieChart.setUsePercentValues(usePercent);            //使用百分比显示
        mPieChart.getDescription().setEnabled(false);    //设置pieChart图表的描述
//        mPieChart.set
        mPieChart.setBackgroundColor(Color.WHITE);      //设置pieChart图表背景色
        mPieChart.setExtraOffsets(5, 10, 5, 5);        //设置pieChart图表上下左右的偏移，类似于外边距
        mPieChart.setDragDecelerationFrictionCoef(0.95f);//设置pieChart图表转动阻力摩擦系数[0,1]  
        mPieChart.setRotationAngle(0);                   //设置pieChart图表起始角度  
        mPieChart.setRotationEnabled(true);              //设置pieChart图表是否可以手动旋转  
        mPieChart.setHighlightPerTapEnabled(true);       //设置piecahrt图表点击Item高亮是否可用  
        mPieChart.animateY(1400, Easing.EasingOption.EaseInOutQuad);// 设置pieChart图表展示动画效果  

       // 设置 pieChart 图表Item文本属性
        mPieChart.setDrawEntryLabels(false);              //设置pieChart是否只显示饼图上百分比不显示文字（true：下面属性才有效果）
        mPieChart.setEntryLabelColor(Color.BLACK);       //设置pieChart图表文本字体颜色
        mPieChart.setEntryLabelTypeface(Typeface.DEFAULT);     //设置pieChart图表文本字体样式
        mPieChart.setEntryLabelTextSize(8f);            //设置pieChart图表文本字体大小

      // 设置 pieChart 内部圆环属性
        mPieChart.setDrawHoleEnabled(true);              //是否显示PieChart内部圆环(true:下面属性才有意义)  
        mPieChart.setHoleRadius(getActivity().getResources().getDimension(R.dimen.piechart_rid));                    //设置PieChart内部圆的半径(这里设置28.0f)
        mPieChart.setTransparentCircleRadius(getActivity().getResources().getDimension(R.dimen.piechart_rid_out));       //设置PieChart内部透明圆的半径(这里设置31.0f)
        mPieChart.setTransparentCircleColor(Color.WHITE);//设置PieChart内部透明圆与内部圆间距(31f-28f)填充颜色
        mPieChart.setTransparentCircleAlpha(50);         //设置PieChart内部透明圆与内部圆间距(31f-28f)透明度[0~255]数值越小越透明  
        mPieChart.setHoleColor(Color.WHITE);             //设置PieChart内部圆的颜色  
        mPieChart.setDrawCenterText(false);               //是否绘制PieChart内部中心文本（true：下面属性才有意义）
//        mPieChart.setCenterTextTypeface(mTfLight);       //设置PieChart内部圆文字的字体样式
//        mPieChart.setCenterText("Test");                 //设置PieChart内部圆文字的内容
//        mPieChart.setCenterTextSize(10f);                //设置PieChart内部圆文字的大小
//        mPieChart.setCenterTextColor(Color.RED);         //设置PieChart内部圆文字的颜色
    }

    //设置数据
    private PieData setData(ArrayList<PieEntry> entries,int type) {
        PieDataSet dataSet = new PieDataSet(entries, "");
        dataSet.setSliceSpace(3f);           //设置饼状Item之间的间隙
        dataSet.setSelectionShift(3f);      //设置饼状Item被选中时变化的距离

        //数据和颜色
        ArrayList<Integer> colors = new ArrayList<>();
        colors.add(getResources().getColor(R.color.char1));
        colors.add(getResources().getColor(R.color.char2));
        colors.add(getResources().getColor(R.color.char3));
        dataSet.setColors(colors);
        PieData data = new PieData(dataSet);
        if(type == 1 ){
            data.setValueFormatter(new DefaultValueFormatter(1));
        }else if(type == 2){
            data.setValueFormatter(new PercentFormatter());
        }
        data.setValueTextSize(9f);
        data.setValueTextColor(Color.WHITE);
        return data;
    }
}
